package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_NULL_TTL;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TTL;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    
    @Override
    public Result queryById(Long id) {
        // 缓存穿透
        // Shop = queryWithPassThrough(id);
        
        // 互斥锁解决缓存击穿问题
        Shop shop = queryWithMutex(id);
        if (shop == null) {
            return Result.fail("店铺不存在！");
        }
        return Result.ok(shop);
    }
    
    public Shop queryWithPassThrough(Long id) {
        // 1.从redis查询店铺信息
        String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        // 2.判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            // 3.存在，直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        // 判断获取到的数据是否是空值
        if (shopJson == null) {
            return null;
        }
        // 4.不存在，根据id查询数据库
        Shop shop = getById(id);
        // 5.数据库不存在，返回错误
        if (shop == null) {
            // 不存在，设置为null进行保存
            stringRedisTemplate.opsForValue().set(
                    RedisConstants.CACHE_SHOP_KEY + id,
                    JSONUtil.toJsonStr(shop),
                    CACHE_NULL_TTL,
                    TimeUnit.MINUTES
            );
            return null;
        }
        // 6.存在，写入redis
        stringRedisTemplate.opsForValue().set(
                RedisConstants.CACHE_SHOP_KEY + id,
                JSONUtil.toJsonStr(shop),
                CACHE_SHOP_TTL,
                TimeUnit.MINUTES
        );
        
        return shop;
    }
    
    public Shop queryWithMutex(Long id) {
        // 1.从redis查询店铺信息
        String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        // 2.判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            // 3.存在，直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        // 判断获取到的数据是否是空值
        if (shopJson == null) {
            return null;
        }
        Shop shop = null;
        
        try {
            // 4.实现缓存重建功能
            // 4.1 获取互斥锁
            boolean flag = tryLock(RedisConstants.LOCK_SHOP_KEY + id);
            // 4.2 判断是否获取成功
            if (!flag) {
                // 4.3 失败，休眠并重试
                Thread.sleep(50);
                // 重试
                return queryWithMutex(id);
            }
            // 4.4 成功，根据id查询数据库，返回数据
            
            // 不存在，根据id查询数据库
            shop = getById(id);
            // 5.数据库不存在，返回错误
            if (shop == null) {
                // 不存在，设置为null进行保存
                stringRedisTemplate.opsForValue().set(
                        RedisConstants.CACHE_SHOP_KEY + id,
                        JSONUtil.toJsonStr(shop),
                        CACHE_NULL_TTL,
                        TimeUnit.MINUTES
                );
                return null;
            }
            // 6.存在，写入redis
            stringRedisTemplate.opsForValue().set(
                    RedisConstants.CACHE_SHOP_KEY + id,
                    JSONUtil.toJsonStr(shop),
                    CACHE_SHOP_TTL,
                    TimeUnit.MINUTES
            );
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 7.释放互斥锁
            unLock(RedisConstants.LOCK_SHOP_KEY + id);
        }
        return shop;
    }
    
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    
    public Shop queryWithLogicalExpire(Long id) {
        // 1.从redis查询店铺信息
        String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        // 2.判断是否存在
        if (StrUtil.isBlank(shopJson)) {
            // 3.不存在，直接返回
            return null;
        }
        // 4.存在,需要判断过期时间
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        // 5.判断是否过期
        LocalDateTime expireTime = redisData.getExpireTime();
        if (expireTime.isAfter(LocalDateTime.now())) {
            // 5.1.未过期,直接返回
            return JSONUtil.toBean(JSONUtil.toJsonStr(redisData.getData()), Shop.class);
        }
        // 5.2.过期，根据id查询数据库
        
        // 6.缓存创建
        // 6.1.获取互斥锁
        boolean flag = tryLock(RedisConstants.LOCK_SHOP_KEY + id);
        // 6.2.判断是否获取成功
        if (flag) {
            // 6.3.成功,开启独立线程,实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                // 缓存重建
                try {
                    this.saveShop2Redis(id, 30L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    // 释放锁
                    unLock(RedisConstants.LOCK_SHOP_KEY + id);
                }
            });
        }
        
        // 6.4.失败,返回过期商品信息
        
        return JSONUtil.toBean(JSONUtil.toJsonStr(redisData.getData()), Shop.class);
    }
    
    // 尝试获取锁
    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    
    // 释放锁
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }
    
    public void saveShop2Redis(Long id, Long expireSeconds) {
        // 1.查询店铺数据
        Shop shop = getById(id);
        // 2.封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        // 3.写入redis
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }
    
    @Override
    @Transactional
    public Result update(Shop shop) {
        // 判断店铺id是否存在
        if (shop.getId() == null) {
            return Result.fail("店铺id不能为空");
        }
        // 1.更新数据库
        updateById(shop);
        // 2.删除缓存
        
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + shop.getId());
        
        return Result.ok();
    }
}
;